﻿using NB.MGJ.Common.API;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace NB.MGJ.API
{
    [ApiAuthorizeFilter]
    //创建于2017011.01 创建人 华君
    public partial class ApiMGJFleedToolsController : ApiBaseController<LogOnUserModel>
    {

        //获取单据编码
        [Route("nbapi/fleedtool/getinfo/formcode")]
        [HttpGet]
        public IHttpActionResult GetFormCode(string formType, string enterpriseId)
        {
            switch (formType)
            {
                case "RK":
                    return ApiSuccess(_flee.GetCode(enterpriseId));
                case "CK":
                    return ApiSuccess(_flee.OutGetCode(enterpriseId));

                case "DH":
                    return ApiSuccess(_flee.TranGetCode(enterpriseId));

                case "DB":
                    return ApiSuccess(_flee.AllocationGetCode(enterpriseId));

                case "TH":
                    return ApiSuccess(_flee.ProReturnGetCode(enterpriseId));
                default:
                    return ApiFail("编码格式不正确");
            }
        }

        //出库验证
        [Route("nbapi/fleedtool/isoutstorage")]
        [HttpGet]
        public IHttpActionResult OutCheck(string code, int userId, int proId)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                return ApiFail("请扫码");
            }
            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(userInfo.EnterpriseId.Value);//获取最上级的机构信息      
            if (code.Trim().Substring(0, 4) != ent.Code)
            {
                return ApiFail("该码不属于当前企业！");
            }
            var digModel = _flee.GetTable(code);
            if (digModel == null) return ApiFail("该码不存在！");
            //码分配
            var allotInfo = new CodeManage_Allot();
            if (ent.ID != userInfo.EnterpriseId)
            {
                allotInfo = _flee.CodeAllotInfo(ent.ID, userInfo.EnterpriseId.Value, code.Trim().Substring(4, 4));
                if (allotInfo == null || allotInfo.AllotType == 2) { return ApiFail("该码不属于当前企业或未分配！"); }
            }
            if (allotInfo.AllotType == 0)//按号段分配
            {
                if (digModel.ID < allotInfo.StartCode || digModel.ID > allotInfo.EndCode)
                {
                    return ApiFail("该码不属于当前企业或未分配");
                }
            }
            if (digModel.ProductId != proId && proId != 0) return ApiFail("该码与之前码的产品不同");
            var list = _flee.ListGetTable(code);
            //判断是否冻结
            if (list[0].Flag != 0) return ApiFail("该码已冻结");
            var parentCode = list[0].Wl_Code;
            if (LogOnUser.Distributor != 0)  //经销商 
            {     //判断是否有出库权限
                var outInfo = _flee.GetOutTable(parentCode);
                if (outInfo == null || outInfo.DistributorID != userInfo.Distributor)
                    return ApiFail("您尚未权限操作该码");

                //判断当前操作人是否对该码做过出库操作
                var isOutInfo = _flee.GetOutInfo(parentCode, userInfo.EnterpriseId.Value);
                if (isOutInfo != null)
                {
                    if (isOutInfo.ChangeLoginID == userInfo.ID)
                    {
                        return ApiFail("该码您已出库，请勿重复！");
                    }
                }
            }
            else//机构
            {
                //判断当前机构是否已出库
                var isOutInfo = _flee.GetOutInfo(parentCode, userInfo.EnterpriseId.Value);
                if (isOutInfo != null && isOutInfo.DistributorID != 0) return ApiFail("该码您已出库，请勿重复！");

            }
            //出库自动拆箱
            if (parentCode != code) {
                bool isTrue = CodeInfoImport(parentCode, code, 4, parentCode);
                if (!isTrue) return Json("出库拆箱时失败");
            }
            cs.ScanCodeHistoryAdd(new string[] { code }, userInfo.ID, 2);
            return ApiSuccess(new { ProductId = digModel.ProductId, state = true });
        }

        /// <summary>
        /// 分离单标公共方法
        /// </summary>
        /// <param name="pCodeMax">最大一级码</param>
        /// <param name="code">本码</param>
        /// <param name="type">操作类型 2 分离单标 4 出库拆箱</param>
        /// <param name="pcode0">直接上级码</param>
        /// <returns></returns>
        public bool CodeInfoImport(string pCodeMax, string code, int type, string pcodeSmall) {
            int i = _flee.AddRecords(pCodeMax, code);
            if (i < 0) return false;
            AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
            record.CZCode = code;
            record.GLCode = pcodeSmall;
            int id = _flee.UpdateParentCode(code, "0");
            if (id > 0) {
                //添加操作记录
                record.Type = 4;//4 出库拆箱 2 分离单标
                record.CreateBy = LogOnUser.UserID;
                record.CreateOn = DateTime.Now;
                _flee.RecordAdd(record);
                return true;
            }
            else {
                return false;
            }
        }

        //调货验证
        [Route("nbapi/fleedtool/dh/check")]
        [HttpGet]
        public IHttpActionResult TranCheck(string code, int userId, int proId)
        {

            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(userInfo.EnterpriseId.Value);//获取最上级的机构信息        
            if (code.Trim().Substring(0, 4) != ent.Code)
            {
                return ApiFail("该码不属于当前企业！");
            }
            var digModel = _flee.GetTable(code);
            if (digModel == null) return ApiFail("该码不存在！");
            //码分配
            var allotInfo = new CodeManage_Allot();
            if (ent.ID != userInfo.EnterpriseId)
            {
                allotInfo = _flee.CodeAllotInfo(ent.ID, userInfo.EnterpriseId.Value, code.Trim().Substring(4, 4));
                if (allotInfo == null || allotInfo.AllotType == 2) { return ApiFail("该码不属于当前企业或未分配"); }
            }
            if (allotInfo.AllotType == 0)//按号段分配
            {
                if (digModel.ID < allotInfo.StartCode || digModel.ID > allotInfo.EndCode)
                {
                    return ApiFail("该码不属于当前企业或未分配");
                }
            }
            if (digModel.ProductId != proId && proId != 0) return ApiFail("该码与之前码的产品不同");
            var list = _flee.ListGetTable(code);
            //判断是否冻结
            if (list[0].Flag != 0) return ApiFail("该码已冻结");
           
            var parentCode = list[0].Wl_Code;
            if (parentCode != code) return ApiFail("请分离后再操作");
            if (userInfo.Distributor != 0)
            {
                var outInfo = _flee.GetOutTable(parentCode);
                if (outInfo == null || outInfo.DistributorID != userInfo.Distributor)
                {
                    return ApiFail("该码您尚未权限操作");
                }
                AntiFleeing_WareHousingDetails dd = _flee.GetIntoTable(code, userInfo.ID.ToString());//查询入库信息
              //  var dd = _flee.GetlastInStorageDetail(code);
             //   if (dd == null || dd.UserID != userInfo.ID) 
                if (dd == null)
                {
                    AntiFleeing_OutboundDetails outModel = _flee.GetOutTable(code); //查询出库信息
                    if (outModel == null || outModel.DistributorID != userInfo.Distributor)
                    {
                        return ApiFail("该码不存在于您的库中");
                    }

                }
            }
            else
            {
                return ApiFail("您尚不能操作该功能");
            }
            cs.ScanCodeHistoryAdd(new string[] { code }, userInfo.ID, 2);
            return ApiSuccess(new { ProductId = digModel.ProductId, state = true });
        }
        //入库验证
        [Route("nbapi/fleedtool/rk/check")]
        [HttpGet]
        public IHttpActionResult InCheck(string code, int userId, int proId)
        {

            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(userInfo.EnterpriseId.Value);//获取最上级的机构信息       
            if (code.Trim().Substring(0, 4) != ent.Code)
            {
                return ApiFail("该码不属于当前企业");
            }
            var digModel = _flee.GetTable(code);
            if (digModel == null) return ApiFail("该码不存在");
            //码分配
            var allotInfo = new CodeManage_Allot();
            if (ent.ID != userInfo.EnterpriseId)
            {
                allotInfo = _flee.CodeAllotInfo(ent.ID, userInfo.EnterpriseId.Value, code.Trim().Substring(4, 4));
                if (allotInfo == null || allotInfo.AllotType == 2) { return ApiFail("该码不属于当前企业或未分配"); }
            }
            if (allotInfo.AllotType == 0)//按号段分配
            {
                if (digModel.ID < allotInfo.StartCode || digModel.ID > allotInfo.EndCode)
                {
                    return ApiFail("该码不属于当前企业或未分配！");
                }
            }
            if (digModel.ProductId != proId && proId != 0) return ApiFail("该码与之前码的产品不同");
            var list = _flee.ListGetTable(code);
            //判断是否冻结
            if (list[0].Flag != 0) return ApiFail("该码已冻结");
            var parentCode = list[0].Wl_Code;
            if (parentCode != code) return ApiFail("请分离后再操作");
            if(userInfo.Distributor!=0)
            {
                //判断权限
                var outInfo = _flee.GetOutTable(parentCode);
                if (outInfo==null||outInfo.DistributorID != userInfo.Distributor) return ApiFail("该码尚未权限操作");
                //判断经销商入库信息
                var inInfo = _flee.IsInStorage_Dist(parentCode,userInfo.Distributor.Value);
                if (!inInfo) return ApiFail("箱码已入库");
             }
            else
            {
                var outInfo = _flee.GetOutTable(parentCode);
                if (outInfo != null) return ApiFail("无权限");
                bool isHas = _flee.GetInStorageInfo(parentCode, userInfo.EnterpriseId.Value);
                if (!isHas) return ApiFail("已入库");
            }


            cs.ScanCodeHistoryAdd(new string[] { code }, userInfo.ID, 2);
            return ApiSuccess(new { ProductId = digModel.ProductId, state = true });
        }

        //调拨验证
        [Route("nbapi/fleedtool/db/check")]
        [HttpGet]
        public IHttpActionResult AllotCheck(string code, int userId, int proId)
        {

            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(userInfo.EnterpriseId.Value);//获取最上级的机构信息     
            if (code.Trim().Substring(0, 4) != ent.Code)
            {
                return ApiFail("该码不属于当前企业！");
            }
            var digModel = _flee.GetTable(code);
            if (digModel == null) return ApiFail("该码不存在！");
            if (digModel.ProductId != proId && proId != 0) return ApiFail("该码与之前码的产品不同");
            var list = _flee.ListGetTable(code);
            //判断是否冻结
            if (list[0].Flag != 0) return ApiFail("该码已冻结");
            var parentCode = list[0].Wl_Code;
            if (parentCode != code) return ApiFail("请分离后再操作");
            var outInfo = _flee.GetOutTable(parentCode);
            if (userInfo.Distributor != 0)
            {
                if (outInfo == null || outInfo.DistributorID != userInfo.Distributor)
                {
                    return ApiFail("该码您尚未权限操作");
                }
                bool isHas = _flee.GetIntoInfo(parentCode, userInfo.ID.ToString());//查询入库信息
                if (!isHas)
                {
                    return ApiFail("该码尚未入库");
                }
            }
            else
            {
                if (outInfo != null && outInfo.DistributorID != userInfo.Distributor)
                {
                    return ApiFail("该码您已出库");
                }
            }

            var dt = _flee.GetIOWarehouseInfo(parentCode, userInfo.EnterpriseId.Value);
            if (dt == null) return ApiFail("该码尚未入库");
            cs.ScanCodeHistoryAdd(new string[] { code }, userInfo.ID, 2);
            return ApiSuccess(new { ProductId = digModel.ProductId, FromWarehouseId = dt.WarehouseId, state = true });
        }

        //退货验证
        [Route("nbapi/fleedtool/th/check")]
        [HttpGet]
        public IHttpActionResult ReturnCheck(string code, int userId, int proId)
        {

            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(userInfo.EnterpriseId.Value);//获取最上级的机构信息       
            if (code.Trim().Substring(0, 4) != ent.Code)
            {
                return ApiFail("该码不属于当前企业");
            }
            var digModel = _flee.GetTable(code);
            if (digModel == null) return ApiFail("该码不存在");
            //码分配
            var allotInfo = new CodeManage_Allot();
            if (ent.ID != userInfo.EnterpriseId)
            {
                allotInfo = _flee.CodeAllotInfo(ent.ID, userInfo.EnterpriseId.Value, code.Trim().Substring(4, 4));
                if (allotInfo == null || allotInfo.AllotType == 2) { return ApiFail("该码不属于当前企业或未分配！"); }
            }
            if (allotInfo.AllotType == 0)//按号段分配
            {
                if (digModel.ID < allotInfo.StartCode || digModel.ID > allotInfo.EndCode)
                {
                    return ApiFail("该码不属于当前企业或未分配");
                }
            }
            if (digModel.ProductId != proId && proId != 0) return ApiFail("该码与之前码的产品不同");
            var list = _flee.ListGetTable(code);
            //判断是否冻结
            if (list[0].Flag != 0) return ApiFail("该码已冻结");
            var parentCode = list[0].Wl_Code;
            if (parentCode != code) return ApiFail("请分离后再操作");
            if (userInfo.Distributor != 0)
            {
                var outInfo = _flee.GetOutTable(parentCode);
                if (outInfo == null || outInfo.DistributorID != userInfo.Distributor)
                {
                    return ApiFail("该码您尚未权限操作");
                }
            }
            else
            {
                return ApiFail("您尚不能操作该功能");
            }

            AntiFleeing_WareHousingDetails dd = _flee.GetIntoTable(parentCode, userInfo.ID.ToString());//查询入库信息

            if (dd == null)
            {
                AntiFleeing_OutboundDetails outModel = _flee.GetOutTable(code); //查询出库信息
                if (outModel == null || outModel.DistributorID != LogOnUser.Distributor)
                {

                    return ApiFail("该码不存在或没有权限操作");

                }

                var outInfo = _flee.GetOutTable(parentCode);
                if (outInfo == null || outInfo.DistributorID != userInfo.Distributor)
                {
                    return ApiFail("该码您尚未权限操作");
                }
                dd = _flee.GetIntoTable(code, userInfo.ID.ToString());//查询入库信息
                if (dd == null)
                {
                    return ApiFail("该码尚未入库");
                }

            }
            cs.ScanCodeHistoryAdd(new string[] { code }, userInfo.ID, 2);
            return ApiSuccess(new { ProductId = digModel.ProductId, state = true });
        }

        //昨日出库数量
        [Route("nbapi/fleedtool/count/boundcount")]
        [HttpGet]
        public IHttpActionResult YesterdayBound(int userId)
        {
            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            string sTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            string eTime = DateTime.Now.ToString("yyyy-MM-dd");

            if (userInfo.Distributor != 0)
            {
                return ApiSuccess(_flee.YstdBoundByDis(userInfo.ID, 2, sTime, eTime));
            }
            else
            {
                return ApiSuccess(_flee.YstdBoundByEnt(userInfo.EnterpriseId.Value, 2, sTime, eTime));
            }

        }
        //昨日入库数量
        [Route("nbapi/fleedtool/count/storagecount")]
        [HttpGet]
        public IHttpActionResult YesterdayStorage(int userId)
        {
            //根据用户id得到用户信息
            Sys_User userInfo = _mservice.GetUserInfoById(userId);
            string sTime = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            string eTime = DateTime.Now.ToString("yyyy-MM-dd");
            if (userInfo.Distributor != 0)
            {
                return ApiSuccess(_flee.YstdBoundByDis(userInfo.ID, 1, sTime, eTime));
            }
            else
            {
                return ApiSuccess(_flee.YstdBoundByEnt(userInfo.EnterpriseId.Value, 1, sTime, eTime));
            }

        }

        //get仓库model
        [Route("nbapi/fleedtool/warehouse/getmodel")]
        [HttpGet]
        public IHttpActionResult GetWarehouseModel(int Id)
        {
            return ApiSuccess(_flee.GetWarehouseInfo(Id));
        }
        //拆箱 code大箱码
        [Route("nbapi/fleedtool/splitbox")]
        [HttpGet]
        public IHttpActionResult SliptCase(string code, int userid) 
        {
            Sys_User user = ms.GetUserInfoById(userid);
            code = code.Trim();
            AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
            record.CZCode = code;
            var list = new List<V_ListBox>();
            string result = Check_Out(code, user,out list);
            if (!string.IsNullOrEmpty(result)) return ApiFail(result);
            record.Type = 1;//拆箱
            record.CreateBy = user.ID;
            record.CreateOn = DateTime.Now;
            fs.AddDevanningRecords(record);
            _flee.AddRecordsforSplit(code);
            int i = _flee.SlipCase(code);
            if (i < 0) return ApiFail("拆箱失败");
            return ApiSuccess("拆箱成功");
         }
        //装箱验证
        [Route("nbapi/fleedtool/fillThebox/check")]
        [HttpGet]
        public IHttpActionResult CaseBoxCheck(string code, int userId)
        {
            Sys_User user = ms.GetUserInfoById(userId);
            var list= new List<V_ListBox>();
            string result = Check_Out(code, user, out list);
            if (!string.IsNullOrEmpty(result)) return ApiFail(result);
            //重复装箱提示 
            if (!string.IsNullOrEmpty(list[list.Count - 1].ParentCode) && list[list.Count - 1].ParentCode != "0") return ApiFail("该码已装箱！");      
            return ApiSuccess(true);
        }
        public string Check_Out(string code, Sys_User LogOnUser, out List<V_ListBox> _list)
        {
            var list = _flee.GetParentCode(code);
            _list = list;
            if (list == null) return "码不存在";
            //判断是否冻结
            if (list[0].Flag != 0) return "该码已冻结";
            Organization_Enterprise ent = _flee.GetMaxEnterpriseIInfo(LogOnUser.EnterpriseId.Value);
            if (LogOnUser.EnterpriseId != 1 && code.Substring(0, 4) != ent.Code.Substring(0, 4)) return "无权限";
            //获取码分配信息
            var allotInfo = new CodeManage_Allot();
            if (ent.ID != LogOnUser.EnterpriseId)
            {
                allotInfo = _flee.CodeAllotInfo(ent.ID, LogOnUser.EnterpriseId.Value, code.Trim().Substring(4, 4));
                if (allotInfo == null || allotInfo.AllotType == 2) { return "无权限"; }
            }
            if (allotInfo.AllotType == 0)//按号段分配
            {
                if (list[list.Count - 1].ID < allotInfo.StartCode || list[list.Count - 1].ID > allotInfo.EndCode)
                {
                    return "无权限";
                }
            }
            var outInfo = _flee.GetOutTable(list[0].Wl_Code);//出库信息
            if (LogOnUser.Distributor != 0)
            {
                if (outInfo == null || outInfo.DistributorID != LogOnUser.Distributor)
                {
                    return "无权限";
                }
            }
            else
            {
                if (outInfo != null)
                {
                    return "该码已出库";
                }
            }
            return null;
        }
    }
}
